<template>
  <div class="company-perm">
    <div class="company-perm-title">
      数据权限
    </div>
    <div class="company-perm-body"> 
      <ElButton
        :class="{ 'company-perm-btn': props.modelValue.includes('ALL') }"
        :plain="props.modelValue.includes('ALL')"
        :type="props.modelValue.includes('ALL') ? 'primary' : 'default'"
        @click="onChange('ALL')"
      >
        全部
        <el-icon v-if="props.modelValue.includes('ALL')" class="company-perm-icon"><Select /></el-icon>
      </ElButton>

      <ElButton
        v-for="item in companyList"
        :class="{ 'company-perm-btn': props.modelValue.includes(item.val) }"
        :key="item.val"
        :plain="props.modelValue.includes(item.val)"
        :type="props.modelValue.includes(item.val) ? 'primary' : 'default'"
        @click="onChange(item.val)"
      >
        {{  item.name }}
        <el-icon v-if="props.modelValue.includes(item.val)" class="company-perm-icon"><Select /></el-icon>
      </ElButton>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { ElButton, ElIcon } from 'element-plus'
import { Select } from '@element-plus/icons-vue'
import { getAllCompany } from '../api'

interface Props {
  modelValue: string[];
  data: object;
}
const props = withDefaults(defineProps<Props>(), {
  modelValue: () => [],
  data: () => ({})
})

interface Emits {
  'update:model-value': [string[]]
}
const emit = defineEmits<Readonly<Emits>>()

const companyList = ref([])
onMounted(async () => {
  companyList.value = await getAllCompany() || []
})

const onChange = val => {
  const list = [...props.modelValue]
  const index = list.findIndex(i => i===val)
  
  if (index !== -1) {
    list.splice(index, 1)
  } else {
    list.push(val)
  }

  emit('update:model-value', list)
}
</script>

<style scoped lang="scss">
.company-perm {
  &-title {
    font-family: PingFangSC-Medium;
    font-weight: 500;
    font-size: 13px;
    color: #333333;
  }
  &-btn {
    position: relative;
    overflow: hidden;
    &::after {
      content: '';
      display: inline-block;
      width: 20px;
      height: 20px;
      background: var(--el-color-primary);;
      position: absolute;
      bottom: -11px;
      right: -9px;
      transform: rotate(50deg);
      z-index: 1;
    }
  }

  &-icon {
    position: absolute;
    right: 1px;
    bottom: 0px;
    font-size: 8px;
    color: var(--el-color-white);
    z-index: 10;
  }
}
</style>
